﻿using System;
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Security.Permissions;

public class NetController  {
    //本机socket
    public Socket MySocket;
    //ipadsocket
    public Socket IpadSocket;
    byte[] buffer = new byte[1024];
#region 单例
    private static NetController instance;
    private NetController()
    {

    }

    public static NetController GetInstance()
    {
        if (instance == null)
        {
            instance = new NetController();
        }
        return instance;
    }
#endregion

    /// <summary>
    /// 初始化socket
    /// </summary>
    public void Init(bool IsServer,string ip,int port)
    {
        IPAddress address = IPAddress.Parse(ip);
        MySocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        EndPoint endPoint = new IPEndPoint(address, port);
        //判断是否是服务器
        if (IsServer)
        {
            //服务器异步监听
            Debug.Log("服务器开始监听，等待连接......");
            MySocket.Bind(endPoint);
            MySocket.Listen(5);
            MySocket.BeginAccept(BeginAcceptIpad, null);
        }
        else
        {
            //主动连接服务器
            MySocket.BeginConnect(endPoint, BeginConnectServer, null);
        }
    }
#region  接收函数
    /// <summary>
    /// 异步接受消息回调
    /// </summary>
    /// <param name="result"></param>
    public void AnsyReceiveMessage(IAsyncResult result)
    {
        Debug.Log("接收到新的消息");
        //Socket MySocket = (Socket) result.AsyncState;
        int length = IpadSocket.EndReceive(result);
        object[] messages = MessageController.GetInstance().ReadMessage(buffer, length);
        NetManager._instance.HandleMessage((short)messages[0],messages[1]);
        buffer = new byte[1024];
        IpadSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, AnsyReceiveMessage, null);
    }
#endregion

#region 发送函数
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="type">消息类型</param>
    /// <param name="message">消息内容</param>
    public void SendMessage<T>(MessageType type, T message)
    {
        Debug.Log("成功发送消息");
        byte[] buffer = MessageController.GetInstance().WriteMessage((short) type,message);
        IpadSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, AnsySend, null);
    }
    /// <summary>
    /// 异步发送消息回调打印
    /// </summary>
    /// <param name="result"></param>
    public void AnsySend(IAsyncResult result)
    {
        int length = IpadSocket.EndSend(result);
        Debug.Log("成功发送消息给ipad,长度为" + length);
    }
#endregion

#region  服务器函数
    /// <summary>
    /// 异步接受Ipad连接到此服务器
    /// </summary>
    /// <param name="rezult"></param>
    public void BeginAcceptIpad(IAsyncResult result)
    {
        IpadSocket = MySocket.EndAccept(result);
        Debug.Log("ipad已连接,开始监听");
        //开始异步接受消息
        IpadSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, AnsyReceiveMessage, null);
    }
#endregion

#region 客户端函数
    public void BeginConnectServer(IAsyncResult result)
    {
        MySocket.EndConnect(result);
        IpadSocket = MySocket;
        Debug.Log("已连接到ipad，开始异步接受消息");
        //开始异步接受消息
        IpadSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, AnsyReceiveMessage, null);
    }
#endregion
}
